<script setup>

import { ref, onMounted } from "vue";
import * as Api from "@req/api";
import { suc, upImgFun } from "@/utils";
import { Modal, message } from "ant-design-vue";
import { LoadingOutlined, PlusOutlined, CloseCircleOutlined } from '@ant-design/icons-vue';
import selectProduct from "@/components/selectProduct/index.vue";
import bannerMod from "@/components/configMod/banner.vue";
import EditorCom from "@/components/EditorCom/index.vue";

const tableLoading = ref(false)
const popLoadig = ref(false)
const fileLoading = ref(false)
const selectShow = ref(false)

const bannerList = ref([])
const showBanner = ref(false)
const bannerIdx = ref(null)
const bannerId = ref(null)
const bannerFrom = ref({
  title: "",
  desc: "",
  image: "",
  link: "",
})
const bcolumns = [
  {
    title: "图片",
    dataIndex: "image",
    key: 'image'
  },
  {
    title: "描述",
    dataIndex: "desc",
  },
  { title: "操作", dataIndex: "action", key: "action" },
];

const bannerSubmt = () => {
  if (bannerIdx.value != null) {
    bannerList.value[bannerIdx.value] = bannerFrom.value
  } else {
    bannerList.value.push(bannerFrom.value)
  }
  let data = {
    title: 'banner',
    content: JSON.stringify(bannerList.value)
  }
  allSubmit(bannerId.value, data)
}

const upFile = async (file) => {
  fileLoading.value = true;
  bannerFrom.value.image = await upImgFun(file)
  fileLoading.value = false;
}

const delImg = () => {
  bannerFrom.value.image = ''
}



const starList = ref([])
const starId = ref(null)
const scolumns = [
  {
    title: "产品名称",
    dataIndex: "name",
  },
  {
    title: "图片",
    dataIndex: "img",
    key: 'img'
  },
  {
    title: "内容",
    dataIndex: "desc",
    ellipsis: true,
  },
  { title: "操作", dataIndex: "action", key: "action" },
];
const starSubmt = () => {
  let data = {
    title: 'star_pord',
    content: JSON.stringify(starList.value)
  }

  allSubmit(starId.value, data)
}


const aboutIdx = ref(null)
const aboutId = ref(null)
const aboutUsList = ref([])
const showAbout = ref(false)
const aboutFrom = ref({
  title: "",
  desc: "",
})
const acolumns = [
  {
    title: "标题",
    dataIndex: "title",
  },
  { title: "操作", dataIndex: "action", key: "action" },
];

const aboutSubmt = () => {
  if (aboutIdx.value != null) {
    aboutUsList.value[aboutIdx.value] = aboutFrom.value
  } else {
    aboutUsList.value.push(aboutFrom.value)
  }
  let data = {
    title: 'about_us',
    content: JSON.stringify(aboutUsList.value)
  }

  allSubmit(aboutId.value, data)
}

onMounted(() => {
  getConfigList()
})

const getConfigList = () => {
  tableLoading.value = true;
  Api.getBlogsList({ blog_type: 'config' }).then((res) => {
    if (suc(res.status)) {
      const resList = res.data.blogs
      resList.map((item) => {
        if (item.title == 'about_us') {
          aboutId.value = item.id
          aboutUsList.value = JSON.parse(item.content)
        }
        if (item.title == 'banner') {
          bannerId.value = item.id
          bannerList.value = JSON.parse(item.content)
        }
        if (item.title == 'star_pord') {
          starId.value = item.id
          starList.value = JSON.parse(item.content)
          console.log(starList.value)
        }
      })
    }
    tableLoading.value = false;
  });
}

const openPop = (type, id) => {
  if (type == 'banner') {
    bannerIdx.value = id
    showBanner.value = true
    id != null && (bannerFrom.value = JSON.parse(JSON.stringify(bannerList.value[id])))
  } else if (type == 'star') {
    selectShow.value = true
  } else {
    aboutIdx.value = id
    showAbout.value = true
    setTimeout(() => {
      id != null && (aboutFrom.value = JSON.parse(JSON.stringify(aboutUsList.value[id])))
    }, 500)
  }
}
const delConfig = (type, index) => {
  if (type == 'banner') {
    bannerList.value.splice(index, 1)
    let data = {
      title: 'banner',
      content: JSON.stringify(bannerList.value)
    }
    allSubmit(bannerId.value, data)
  } else if (type == 'star') {
    starList.value.splice(index, 1)
    let data = {
      title: 'star_pord',
      content: JSON.stringify(starList.value)
    }
    allSubmit(starId.value, data)
  } else {
    aboutUsList.value.splice(index, 1)
    let data = {
      title: 'about_us',
      content: JSON.stringify(aboutUsList.value)
    }
    allSubmit(aboutId.value, data)
  }
}

const openPord = () => {
  selectShow.value = true
}

const allSubmit = (id, data) => {
  const resFun = (res) => {
    if (suc(res.status)) {
      message.success(res.message);
      handleCancel();
      getConfigList()
    } else {
      message.error("添加失败");
    }
  }
  if (id) {
    Api.editBlog(id, data).then((res) => {
      resFun(res)
    });
  } else {
    data['author'] = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')).username : ''
    data['blog_type'] = 'config'
    Api.addBlog(data).then((res) => {
      resFun(res)
    })

  }
}

const handleCancel = () => {
  bannerFrom.value = {
    title: "",
    desc: "",
    image: "",
    link: "",
  }
  aboutFrom.value = {
    title: "",
    desc: "",
  }
  showBanner.value = false
  showAbout.value = false
}

const selectPd = (data) => {
  if (data.type) {
    if (showBanner.value) {
      bannerFrom.value.link = data.data
    } else {
      starList.value.push(data.data)
      starSubmt()
    }
  }
  selectShow.value = false
}

</script>

<template>
  <div class="config-main">
    <!-- <bannerMod :list="bannerList" :id="bannerId"></bannerMod> -->
    <div class="config-part">
      <div class="config-title">banner
        <a-button type="primary" size="small" style="margin-left: 10px;" @click="openPop('banner', null)"
          v-if="bannerList.length < 5">添加</a-button>
      </div>
      <a-table :columns="bcolumns" :data-source="bannerList" :loading="tableLoading" :pagination="false">
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'image'">
            <a-image :src="record.image" class="img-box" width="120px" height="50px" />
          </template>
          <template v-if="column.key === 'action'">
            <span class="table-operation">
              <a-button type="link" @click="openPop('banner', index)">修改</a-button>
              <a-button type="link" danger @click="delConfig('banner', index)">删除</a-button>
            </span>
          </template>
        </template>
      </a-table>
    </div>
    <a-modal v-model:open="showBanner" :title="bannerIdx !== null ? '修改banner' : '添加banner'" width="800px"
      @cancel="handleCancel(true)" :maskClosable="false">
      <a-form :model="bannerFrom" name="basic" class="login-form" autocomplete="off" @finish="bannerSubmt">
        <a-form-item label="图片" name="image">
          <div class="upload-box">
            <div class="up-img" v-if="bannerFrom.image">
              <a-image :src="bannerFrom.image" width="240px" height="100px" alt="main-img" />
              <close-circle-outlined class="close-icon" @click="delImg('img')" />
            </div>
            <a-upload v-else name="avatar" list-type="picture-card" class="avatar-uploader" :customRequest="upFile"
              :show-upload-list="false">
              <div>
                <loading-outlined v-if="fileLoading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          </div>
          <span class="tips">tips: 建议图片比例 <span>12</span> ：<span>5</span></span>
        </a-form-item>
        <a-form-item label="描述" name="desc">
          <a-input v-model:value="bannerFrom.desc" placeholder="输入banner描述" />
        </a-form-item>
        <!-- <a-form-item label="关联产品" name="link" :rules="[{ required: true, message: '请选择关联产品' }]">
          <a-button type="link" style="margin-right: auto;margin-left: 0;" @click="openPord()">{{ bannerFrom.link ?
            bannerFrom?.link?.name : '选择关联产品' }}</a-button>

        </a-form-item> -->
        <a-button type="primary" html-type="submit" :loading="popLoadig">提交</a-button>
      </a-form>
      <template #footer>
      </template>
    </a-modal>


    <div class="config-part">
      <div class="config-title">推荐产品
        <a-button type="primary" size="small" style="margin-left: 10px;" @click="openPop('star', null)"
          v-if="starList.length < 8">添加</a-button>
      </div>
      <a-table :columns="scolumns" :data-source="starList" :loading="tableLoading" :pagination="false">
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'img'">
            <a-image :src="record.img" class="img-box" width="80px" height="80px" />
          </template>
          <template v-if="column.key === 'action'">
            <span class="table-operation">
              <a-button type="link" danger @click="delConfig('star', index)">删除</a-button>
            </span>
          </template>
        </template>
      </a-table>
    </div>


    <div class="config-part">
      <div class="config-title">关于我们
        <a-button type="primary" size="small" style="margin-left: 10px;" @click="openPop('about', null)"
          v-if="aboutUsList.length < 3">添加</a-button>
      </div>
      <a-table :columns="acolumns" :data-source="aboutUsList" :loading="tableLoading" :pagination="false">
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'action'">
            <span class="table-operation">
              <a-button type="link" @click="openPop('about', index)">修改</a-button>
              <a-button type="link" danger @click="delConfig('about', index)">删除</a-button>
            </span>
          </template>
        </template>
      </a-table>
    </div>
    <a-modal v-model:open="showAbout" width="800px" :title="aboutIdx !== null ? '修改关于我们' : '添加关于我们'"
      @cancel="handleCancel(true)" :maskClosable="false">
      <a-form :model="aboutFrom" name="basic" class="login-form" autocomplete="off" @finish="aboutSubmt">
        <a-form-item label="标题" name="title" :rules="[{ required: true, message: '请输入标题' }]">
          <a-input v-model:value="aboutFrom.title" placeholder="输入标题" />
        </a-form-item>
        <a-form-item label="内容" name="desc" :rules="[{ required: true, message: '请输入内容' }]">
          <EditorCom v-if="showAbout" :value="aboutFrom.desc" @changeValue="(val) => { aboutFrom.desc = val }">
          </EditorCom>
          <!-- <a-textarea v-model:value="aboutFrom.desc" placeholder="输入内容" :rows="4" /> -->
        </a-form-item>
        <a-button type="primary" html-type="submit" :loading="popLoadig">提交</a-button>
      </a-form>
      <template #footer>
      </template>
    </a-modal>
    <selectProduct :open="selectShow" :selectId="bannerFrom.link.id" @close="selectPd"></selectProduct>
  </div>
</template>

<style lang="postcss" scoped>
.config-main {
  padding: 16px;
  position: relative;

  .config-part {
    margin-bottom: 50px;

    .config-title {
      font-size: 22px;
      font-weight: bold;
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }
  }

  ::v-deep .ant-image {
    border-radius: 5px;
    overflow: hidden;

    .ant-image-img {
      object-fit: cover;
    }
  }
}

.login-form {
  padding: 20px 20px 0;

  .ant-btn {
    display: block;
    margin-left: auto;
  }

  .upload-box {
    ::v-deep .ant-upload {
      overflow: hidden;
      width: 240px;
      height: 100px;
      box-sizing: border-box;

      &.ant-upload-select {
        width: 240px;
        height: 100px;
        box-sizing: border-box;
      }
    }
  }

  .up-img {
    position: relative;
    width: 240px;
    height: 100px;

    &.list {
      width: 100px;
      height: 100px;
    }

    ::v-deep .ant-image {
      border-radius: 10px;
      overflow: hidden;

      .ant-image-img {
        object-fit: cover;
      }
    }

    .close-icon {
      position: absolute;
      z-index: 1;
      font-size: 25px;
      right: -10px;
      top: -10px;
      cursor: pointer;
    }
  }
}

.tips {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);

  span {
    color: #ff4d4f;
  }
}
</style>